<template>
  <div class="flex b-#d9d9d9 b-1">
    <Input
      class="b-rd-0 b-0"
      :disabled="loading"
      style="min-width: 120px"
      size="large"
      :defaultValue="props.code"
      @change="textChange"
      :maxlength="4"
      :placeholder="t('sys.login.imageCode')"
    />
    <div @click="loadImagecode" class="b-l-#d9d9d9 bg-#eee b-l-1">
      <img :src="image" alt="验证码" class="h-40px" style="flex-shrink: 1" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { Input } from 'ant-design-vue';
  import { ChangeEventHandler } from 'ant-design-vue/es/_util/EventInterface';
  import { getImageCode } from '@/api/sys/user';
  import { useI18n } from '@/hooks/web/useI18n';

  const { t } = useI18n();

  interface ImageCodeData {
    code?: string;
    codeKey?: string;
  }
  interface ImageCodeEmit {
    (e: 'update:code', code: string): void;
    (e: 'update:codeKey', code: string): void;
  }
  const props = defineProps<ImageCodeData>();
  const emits = defineEmits<ImageCodeEmit>();
  const textChange: ChangeEventHandler = (e) => {
    emits('update:code', e.target.value!);
  };
  const image = ref<string>('');
  const loading = ref(false);
  const loadImagecode = () => {
    loading.value = true;
    getImageCode()
      .then((res) => {
        loading.value = false;
        image.value = res.image;
        emits('update:codeKey', res.key);
      })
      .catch((err) => {
        loading.value = false;
      });
  };

  onMounted(() => {
    loadImagecode();
  });

  defineExpose({
    loadImagecode,
  });
</script>
<style lang="less" scoped></style>
